#!/bin/bash
#
# This script runs ci/build in a Docker container.

if [ $# -eq 0 ] || [ ${1:-} = -h ] || [ ${1:-} = --help ]; then
    cat <<EOF
Usage: build-in-docker NAME [ARGUMENTS]

NAME: Subdirectory name in the dockerfiles directory.
ARGUMENTS: Arguments that will be passed to ci/build.
EOF
    exit 1
fi

set -eu

if [ -n "${VERBOSE:-}" ]; then
    set -x
fi

name=${1}
shift

top_dir="$(dirname "$(realpath "$0")")/.."
tag="ccache-build:$name"
command="${COMMAND:-/source/ci/build}"
interactive="${INTERACTIVE:+--interactive --tty}"
nocache="${NOCACHE:+--no-cache}"

# Build (if not exists):
docker build -t "$tag" ${nocache} "${top_dir}/dockerfiles/$name"

# Cache compilation across docker sessions
mkdir -p "${top_dir}/build-in-docker"
mkdir -p "${top_dir}/build-in-docker/docker-ccache"

docker run \
    --init \
    --rm \
    --volume "${top_dir}:/source" \
    --volume "${top_dir}/build-in-docker/docker-ccache:/ccache" \
    --tmpfs /builddir:rw,exec \
    --workdir /builddir \
    --env ASAN_OPTIONS="${ASAN_OPTIONS:-}" \
    --env EXTRA_CMAKE_BUILD_FLAGS="${EXTRA_CMAKE_BUILD_FLAGS:-}" \
    --env CC="${CC:-}" \
    --env CCACHE_DIR=/ccache \
    --env CCACHE_LOC="/source" \
    --env CFLAGS="${CFLAGS:-}" \
    --env CMAKE_PARAMS="${CMAKE_PARAMS:-}" \
    --env CXX="${CXX:-}" \
    --env CXXFLAGS="${CXXFLAGS:-}" \
    --env LDFLAGS="${LDFLAGS:-}" \
    --env NO_TEST="${NO_TEST:-}" \
    --env SCAN_BUILD="${SCAN_BUILD:-}" \
    --env SPECIAL="${SPECIAL:-}" \
    --env VERBOSE="${VERBOSE:-}" \
    $interactive \
    "$tag" \
    "$command" "$@"
